<?php
/**
 * Created by PhpStorm.
 * User: sunbo
 * Date: 2019/7/3
 * Time: 9:45 AM
 */
namespace app\index\controller;
use think\Exception;
class Sellout extends CoinBaseContorller
{
    /**
     *
     * @api {post} api/sellout/GetListSellOut 获取转出列表
     * @apiDescription  获取转出列表
     * @apiName Select_Menu
     * @apiGroup sellout
     * @apiParam {string} begindate 起始日期
     * @apiParam {string} enddate   结束日期
     * @apiParam {string} page      分页数 1 开始
     * @apiParam {string} count     每页数据量
     * @apiSuccess {string} billdatetime  申请日期
     * @apiSuccess {string} sellout_address 转出地址
     * @apiSuccess {string} purchasein_address 转入地址
     * @apiSuccess {string} fee 手续费
     * @apiSuccess {string} sellout_count 转出数量
     * @apiSuccess {string} status 0 申请中 1 已完成 -1 失败
     * @apiSuccess {string} message  备注
     * @apiSuccess {string} phone 转出申请人
     * @apiSuccess {string} coinname  币种
     * @apiVersion 1.0.1
     */
   public  function GetListSellOut(){
       $begindate=$this->param("begindate");
       $enddate=$this->param("enddate");
       $page=$this->param("page");
       $count=$this->param("count");
      return $this->_GetListSellOut($begindate,$enddate,$page,$count);
   }

   function _GetListSellOut($begindate,$enddate,$page,$count){
       $sql="SELECT a.guid,a.billdatetime,a.sellout_address,a.purchasein_address,a.fee/POW(10,8) fee,a.tokencount/POW(10,8) sellout_count,a.status,a.message, b.phone,c.name coinname from token_bill_transaction_coin a INNER JOIN token_sys_user b on b.guid=a.token_sys_user_guid INNER JOIN token_sys_coin c on c.guid=a.token_sys_coin_guid
  WHERE  a.type=1 and a.billdate  BETWEEN '".$begindate."' and '".$enddate."' and [选择条件]" ;

       $sql=str_replace("[选择条件]"," 1=1 ",$sql);
       $result =$this->SetReportPagination($sql,$page,$count);
      return $this->json_data($result,"");
   }


    /**
     *
     * @api {post} api/sellout/SellOutAuditing  web后台转出确认
     * @apiDescription  后台转出确认
     * @apiGroup sellout
     * @apiParam {string} guid  获取转出列表里的guid
     * @apiSuccess {string}  data  返回空字符表示成功，此时刷新界面
     * @apiVersion 1.0.1
     */
    public  function SellOutAuditing(){
        try{
           $guid=$this->param("guid");
           $this->_SellOutAuditing($guid);
           return $this->json_data("","");
        }catch (Exception $e){
            return $this->json_data("",$e->getMessage());
        }
    }

  public  function  _SellOutAuditing($guid){
        $row=$this->db_select("select b.keyname from token_bill_transaction_coin a INNER JOIN token_sys_coin b on b.guid=a.token_sys_coin_guid where a.guid='".$guid."'");
        if(count($row)==0){
            exception("交易单据查询失败");
            return;
        }
        switch ($row[0]["keyname"]){
            case "USDT":
                $this->send_USDT($guid);
                break;
            case "CUSTOMB":
                $this->send_CUSTOMB($guid);
                break;
            case "":
                break;
            default:
                break;
        }

    }

    function send_CUSTOMB($guid){
       $chan= new  Blockchain();
       $chan->Send_CustomCoin($guid);
    }

    //USDT 转账确认
    function send_USDT($guid){
        $row=$this->db_select("select a.tokencount,c.citpay_phone,c.countries_num,a.token_sys_user_guid from token_bill_transaction_coin a INNER JOIN token_sys_coin b on b.guid=a.token_sys_coin_guid INNER JOIN token_sys_user c on c.guid=a.token_sys_user_guid where a.guid='".$guid."'");
        $amount=$row[0]["tokencount"];
        $userid=$row[0]["token_sys_user_guid"];
        $citPayApi=new CitPayApi();
        $citpay_billno= $citPayApi->_Cit_Pay_outcomeOrder($amount/pow(10,8),$userid);
        $this->db_exec(array("update token_bill_transaction_coin set citpay_billno='".$citpay_billno."',status=1 where guid='".$guid."'"));
    }

    /**
     *
     * @api {post} api/sellout/GetFeeAndCount  转出-获取余额矿工
     * @apiDescription  获取余额和矿工费
     * @apiGroup sellout
     * @apiParam {string} coinguid 币guid
     * @apiSuccess {string}  tokencount  币数量
     * @apiSuccess {string}  fee 手续费
     * @apiVersion 1.0.1
     */
    public function  GetFeeAndCount(){
      $userid=$this->getuserGuid();
      $coinguid=$this->param("coinguid");
      $data=$this->_GetFeeAndCount($coinguid,$userid);
      return $this->json_data($data,"");
    }


    function  _GetFeeAndCount($coinguid,$userid){
        $count =$this->GetCoinCount($coinguid,$userid);
        $fee=$this->GetCoinFee($coinguid);
        $row=$this->GetCoinInfo("1");
        return array("tokencount"=>$count/pow(10,8),"fee"=>$fee/pow(10,8),"unit"=>$row[0]["name"]);
    }



    /**
     *
     * @api {post} api/sellout/Submit  APP转出-提交
     * @apiDescription  提交
     * @apiGroup sellout
     * @apiParam {string} coinguid 币guid
     * @apiParam {string} tokencount 转出数量
     * @apiParam {string} transaction_pwd 交易密码
     * @apiParam {string} address 收款地址
     *
     * @apiSuccess {string} data  空字符 成功
     * @apiVersion 1.0.1
     */
    public function Submit(){
        $userid=$this->getuserGuid();
        $tokencount=$this->param("tokencount")*pow(10,8);
        $transaction_pwd=$this->GetRSA($this->param("transaction_pwd"));
        $address=$this->param("address");
        $coinguid=$this->param("coinguid");
        return $this->json_data("",$this->_Submit($userid,$tokencount,$coinguid,$transaction_pwd,$address));
    }

    function _isCheckAddress($coinguid,$address){
        $result=true;
        if($this->IsCustomCoin($coinguid)){
            $chain=new Blockchain();
            $result=$chain->Custom_ValidateAddress($address);
        }else{

        }
        return $result;
    }

    function  checkCount($tokencount,$coinguid,$type){
        $row=$this->db_select("select sellout_min_count*pow(10,8) sellout_min_count,comein_min_count*pow(10,8) comein_min_count from token_sys_count_control  WHERE token_sys_coin_guid='".$coinguid."'");
        if(count($row)==0){
            return true;
        }

        //出金
        if($type=="sellout"){
            $count=$row[0]["sellout_min_count"];
            if($count<0){
                return true;
            }
            if($count>$tokencount){
                return false;
            }
        }
        //入金
        if($type=="comein"){
            $count=$row[0]["comein_min_count"];
            if($count<0){
                return true;
            }
            if($count>$tokencount){
                return false;
            }
        }
       return true;
    }

    public function  _Submit($userid,$tokencount,$coinguid,$transaction_pwd,$address){
        try{
//         if(!$this->checkCount($tokencount,$coinguid,"sellout")){
//             return "输入数量低于最少数量";
//         }

            if(!$this->_isCheckAddress($coinguid,$address)){
                return "接收地址解析出错";
            }

        if(!$this->CheckTransactionPwd($userid,$transaction_pwd)){
            return "交易密码错误";
        }
        if(strlen($address)==0){
            return "交易地址不能为空";
        }



        //获取手续费
        $fee=$this->GetCoinFee($coinguid);
        $coincount= $this->GetCoinCount($coinguid,$userid);
        $selloutaddress="";
        //如果转出的是代币 则用转出数量+手续费<余额
        if($this->IsCustomCoin($coinguid)){
            $chain=new Blockchain();
            //代币才具有转出地址
            $selloutaddress=$chain->GetCustom_Coin_address($userid);
            if($tokencount+$fee>$coincount){
                return "代币余额不足";
            }
        }else{
            //如果不是代币,需要查看余额
            $user_coincount=$this->GetUserCustomCoinCount($userid);
            if($fee>$user_coincount){
                return "代币手续费余额不足";
            }
            if($tokencount>$coincount){
                return "代币余额不足";
            }
        }


        $uuid=$this->uuid();
        $txid = str_replace('-','','PlusToken'.$this->uuid());
        $array=array("insert into token_bill_transaction_coin(guid,billdate,billdatetime,token_sys_user_guid,sellout_address,fee,tokencount,token_sys_coin_guid,type,purchasein_address,status,citpay_billno) VALUES
('".$uuid."','".date("Y-m-d")."','".date("Y-m-d H:i:s")."','".$userid."','".$selloutaddress."',".$fee.",".$tokencount.",'".$coinguid."',1,'".$address."',0,'".$txid."')");
        //扣手续费
        $array[]="update token_user_custom_coin_balance set token_count=token_count-".$fee." WHERE token_sys_user_guid='".$userid."'";
        if($this->IsCustomCoin($coinguid)){
            //扣交易费
            $array[]="update token_user_custom_coin_balance set token_count=token_count-".$tokencount." WHERE token_sys_user_guid='".$userid."'";
        }
           $this->db_exec($array);
           return "";

        }catch (Exception $e){
           return $e->getMessage();
        }
    }


    /**
     *
     * @api {post} api/sellout/Send_CustomCoin  web 代币转出
     * @apiDescription  代币转出
     * @apiGroup sellout
     * @apiParam {string} guid 转出单据的guid
     *
     * @apiSuccess {string} data  空字符 成功
     * @apiVersion 1.0.1
     */
    public function Send_CustomCoin(){
        try{
            $guid=$this->param("guid");
            $this->_Send_CustomCoin($guid);
            return  $this->json_data("","");
        }catch (Exception $ex){
            return  $this->json_data("",$ex->getMessage());
        }

    }


    public  function _Send_CustomCoin($guid){
        $row=$this->db_select("SELECT guid,status,purchasein_address,citpay_billno,token_sys_coin_guid,tokencount,token_sys_user_guid from token_bill_transaction_coin where guid='".$guid."'");
        if($row[0]["status"]!=0){
            exception("只有已提交的可以提币");
            return;
        }
        $coinguid=$row[0]["token_sys_coin_guid"];
        $address=$row[0]["purchasein_address"];
        $tokencount=$row[0]["tokencount"];
        $txid = $row[0]["citpay_billno"];
        $userid=$row[0]["token_sys_user_guid"];
        if($this->IsCustomCoin($coinguid)) {
            $chain = new Blockchain();
            $chain->Send_CustomCoin($guid);
        }else{
            $citpay_api=new CitPayApi();
            try{
                $result=$citpay_api->_Cit_Pay_outcomeOrder($tokencount/pow(10,8),$userid,$address,$txid);
                if($result["message"]=="success"){
                    $this->db_exec(array("update token_bill_transaction_coin set status=2,citpay_billno='".$txid."' where guid='".$guid."'"));
                }
            }catch (Exception $ex){
                $this->db_exec(array("update token_bill_transaction_coin set message='".$ex->getMessage()."',status=-1 where guid='".$guid."'"));
            }

        }
    }

    /**
     *
     * @api {post} api/sellout/ShowAddress  转入-显示地址
     * @apiDescription  转入
     * @apiGroup sellout
     * @apiParam {string} coinguid 币guid
     *
     * @apiSuccess {string} address  地址
     * @apiVersion 1.0.1
     */
    public function ShowAddress(){
        $userid=$this->getuserGuid();
        $coinguid=$this->param("coinguid");
        return $this->GetAddressFromUserAndCoinGuid($userid,$coinguid);
    }

}